package com.yedean.factory.aop.framework;

import com.yedean.factory.aop.AdvisedSupport;
import org.aopalliance.intercept.MethodInterceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKDynamicAopProxy implements AopProxy, InvocationHandler {
    
    private final AdvisedSupport advised;

    public JDKDynamicAopProxy(AdvisedSupport advisedSupport) {
        this.advised = advisedSupport;
    }
    
    
    @Override
    public Object getProxy() {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),advised.getTargetSource().getTargetClass(),this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //匹配方法
        //匹配成功调用拦截器下的invoke方法
        if (advised.getMethodMatcher().matches(method,advised.getTargetSource().getTarget().getClass())){
            MethodInterceptor interceptor = advised.getMethodInterceptor();
            return interceptor.invoke(new ReflectiveMehtodInvocation(advised.getTargetSource().getTarget(),method,args));
        }
        //匹配不成功则正常方法反射调用
        return method.invoke(advised.getTargetSource().getTarget(),args);
        
    }
}
